package backend

import (
	"chatgpt/controller/father"
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/plugin/found"
	"github.com/gin-gonic/gin"
	"github.com/slclub/go-tips"
	"github.com/slclub/go-tips/json"
)

func AddIndexHandle(ctx *gin.Context) {
	database := ctx.Query("database")
	raw, _ := ctx.Get("RawAny")
	rawmap, ok := raw.(map[string]any)
	if !ok {
		helper.Count(ctx, code.REQ_PARAM_ERR, nil)
		return
	}

	text, ok := rawmap["text"]
	document_any, ok1 := rawmap["document"]
	if !ok1 {
		helper.Count(ctx, code.REQ_PARAM_ERR, nil)
		return
	}
	document, ok := document_any.(map[string]any)
	if !ok {
		str, ok := document_any.(string)
		if ok {
			json.Unmarshal([]byte(str), &document)
		}
	}

	err := found.Default.IndexAdd(uint32(tips.Any2Int64(rawmap["id"])), tips.String(text), (document), database)
	if err != nil {
		logq.ErrorF("BACKEND.GOFOUND.ADD_INDEX err:%v", err)
		helper.Count(ctx, code.SERVER_GOFOUND__ADD_INDEX, nil)
		return
	}
	helper.Count(ctx, code.SUCCESS, nil)
}

func RemoveIndexHandle(ctx *gin.Context) {
	idtr := father.RawAny(ctx, "id")
	id := uint32(tips.Any2Int64(idtr))
	if id <= 0 {
		helper.Count(ctx, code.REQ_PARAM_ERR, nil)
		return
	}
	err := found.Default.IndexRemove(id)
	if err != nil {
		logq.ErrorF("BACKEND.GOFOUND.INDEX-REMOVE err:%v", err)
		helper.Count(ctx, code.SERVER_GOFOUND__REMOVE_INDEX, nil)
		return
	}
	helper.Count(ctx, code.SUCCESS, nil)
}

func IndexQuery(ctx *gin.Context) {
	query := father.RawAny(ctx, "query")
	data := found.Data{}
	err := found.Default.AutoQuery(&data, query.(string), map[string]any{})
	if err != nil {
		logq.ErrorF("BACKEND.GOFOUND.INDEX-REMOVE err:%v", err)
		helper.Count(ctx, code.SERVER_GOFOUND__QUERY_INDEX, nil)
		return
	}
	helper.Count(ctx, code.SUCCESS, data)
}

// ===============================================
// functions
